package com.imgo.max.experience.service;

import com.imgo.max.artist.dto.DevoteInfo;
import com.imgo.max.common.log.CustomLogger;
import com.imgo.max.common.log.CustomLoggerFactory;
import com.imgo.max.core.utils.JsonUntils;
import com.imgo.max.experience.dao.UserExperienceMapper;
import com.imgo.max.experience.dao.UserExperienceMappingMapper;
import com.imgo.max.experience.dto.UserExperienceDto;
import com.imgo.max.experience.mapping.UserExperienceLog;
import com.imgo.max.experience.mapping.UserExperienceMapping;
import com.imgo.max.user.inter.constant.UserConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户经验消息处理类
 *
 * @Auth peter.Y
 * @Date 2016/07/27.
 */
@Component
public class UserExperienceHandler extends ExperienceHandlerParent {

    private static final CustomLogger logger = CustomLoggerFactory.getLogger(UserExperienceHandler.class);

    //经验等级对照表
    private List<UserExperienceMapping> exprMappingList;

    @Autowired
    UserExperienceMapper userExperienceMapper;

    @Resource
    UserExperienceMappingMapper experienceMapping;

    @Override
    protected UserExperienceMapper getExprMapper() {
        return userExperienceMapper;
    }

    @Override
    protected String getRedisKey() {
        return UserConstant.REDIS_ALL_USER_TOTAL_EXPERIENCE_KEY;
    }

    @Override
    protected UserExperienceDto newDtoInstance() {
        return new UserExperienceDto();
    }

    @Override
    protected void initExprMappingList() {
        exprMappingList = experienceMapping.queryExperienceMapping();
    }

    public List<UserExperienceMapping> getExprMappingList() {
        return exprMappingList;
    }

    /**
     * 处理送礼加经验
     *
     * @param devoteInfo
     */
    public void handleMessage(DevoteInfo devoteInfo) {
        String uid = devoteInfo.getUid();
        if (StringUtils.isBlank(uid)) {
            logger.warn("累加经验的用户ID为空,忽略累加");
            return;
        }
        boolean addSuccess = false;
        try {
            int result = addDbExperience(uid, devoteInfo.getDevoteValue());
            if (result > 0) {
                addSuccess = true;
                freshExperience(uid);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("add user experience failed, messageId: {}", devoteInfo.getMessageId());
        } finally {
            try {
                UserExperienceLog log = new UserExperienceLog();
                log.setUid(devoteInfo.getUid());
                log.setGiftId(devoteInfo.getGid());
                log.setMessageId(devoteInfo.getMessageId());
                log.setSource(String.valueOf(devoteInfo.getType()));//贡献来源
                log.setValue(devoteInfo.getDevoteValue());
                log.setTime(devoteInfo.getTime());
                log.setToUid(devoteInfo.getArtistUid());
                log.setResult(addSuccess + "");
                userExperienceMapper.addExperienceLog(log);
            } catch (Exception e) {
                //如果消息中包含“MQ:”,则该日志会打印到failed_message.log日志中去
                logger.error("User experience MQ:{}, add result:{}, content:{}", devoteInfo.getMessageId(), addSuccess, JsonUntils.toJson(devoteInfo), e);

            }
        }
    }

    @Override
    protected Integer getLevel(Integer expr) {
        Integer result = 0;
        //要保证集合的顺序是从小到大
        for (UserExperienceMapping mapping : exprMappingList) {
            result = mapping.getLevel();
            if ((mapping.getEndScore() == null) || (mapping.getEndScore() >= expr)) {
                return result;
            }
        }
        return result;
    }

    @Override
    protected String getRole() {
        // 普通用户
        return "0";
    }

}
